/**
 * Created by kangm_000 on 2017/2/17 0017.
 *
 * 图片压缩工具类
 */
App.convertImgToBase64 = function(url, dir, size, callback, outputFormat) {
  var canvas = document.createElement('CANVAS');
  var ctx = canvas.getContext('2d');
  var img = new Image();
  img.crossOrigin = 'Anonymous';
  img.onload = function() {
    var width = img.width;
    var height = img.height;

    var rate = 1;
    // 图片过大则按比例压缩
    /*   if(size > 200 * 1024){
      rate = (200 * 1024) / size ;
    }*/
    canvas.width = width * rate;
    canvas.height = height * rate;
    ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate);
    var dataURL = canvas.toDataURL(outputFormat || 'image/png');
    //callback.call(this, dataURL);
    App.getImgData(dataURL, dir, callback);
    canvas = null;
  };
  img.src = url;
};

App.getObjectURL = function(file) {
  var url = null;
  if (window.createObjectURL != undefined) {
    // basic
    url = window.createObjectURL(file);
  } else if (window.URL != undefined) {
    // mozilla(firefox)
    url = window.URL.createObjectURL(file);
  } else if (window.webkitURL != undefined) {
    // web_kit or chrome
    url = window.webkitURL.createObjectURL(file);
  }
  return url;
};

// @param {string} img 图片的base64
// @param {int} dir exif获取的方向信息
// @param {function} next 回调方法，返回校正方向后的base64
App.getImgData = function(img, next) {
  var image = new Image();
  image.onload = function() {
    var degree = 0,
      drawWidth,
      drawHeight,
      width,
      height;
    drawWidth = this.naturalWidth;
    drawHeight = this.naturalHeight;
    //以下改变一下图片大小
    var maxSide = Math.max(drawWidth, drawHeight);
    if (maxSide > 1024) {
      var minSide = Math.min(drawWidth, drawHeight);
      minSide = (minSide / maxSide) * 1024;
      maxSide = 1024;
      if (drawWidth > drawHeight) {
        drawWidth = maxSide;
        drawHeight = minSide;
      } else {
        drawWidth = minSide;
        drawHeight = maxSide;
      }
    }
    var canvas = document.createElement('canvas');
    canvas.width = width = drawWidth;
    canvas.height = height = drawHeight;
    var context = canvas.getContext('2d');
    //判断图片方向，重置canvas大小，确定旋转角度，iphone默认的是home键在右方的横屏拍摄方式
    // switch (dir) {
    //   //iphone横屏拍摄，此时home键在左侧
    //   case 3:
    //     degree = 180;
    //     drawWidth = -width;
    //     drawHeight = -height;
    //     break;
    //   //iphone竖屏拍摄，此时home键在下方(正常拿手机的方向)
    //   case 6:
    //     canvas.width = height;
    //     canvas.height = width;
    //     degree = 90;
    //     drawWidth = width;
    //     drawHeight = -height;
    //     break;
    //   //iphone竖屏拍摄，此时home键在上方
    //   case 8:
    //     canvas.width = height;
    //     canvas.height = width;
    //     degree = 270;
    //     drawWidth = -width;
    //     drawHeight = height;
    //     break;
    // }
    //使用canvas旋转校正
    context.rotate((degree * Math.PI) / 180);
    context.drawImage(this, 0, 0, drawWidth, drawHeight);
    //返回校正图片
    next(canvas.toDataURL('image/jpeg', 0.5));
  };
  image.src = img;
};
App.getNewImg = function(base64, next) {
  //创建一个图片
  var newImage = new Image();
  var quality = 0.6; //压缩系数0-1之间，压缩到0.9以上会有bug，注意！（可以自行设置）
  newImage.src = base64;
  newImage.setAttribute('crossOrigin', 'Anonymous'); //url为外域时需要
  var imgWidth, imgHeight;
  newImage.onload = function() {
    imgWidth = this.width;
    imgHeight = this.height;
    //给生成图片设置一个默认的最大宽/高（可以自行设置）
    let myWidth = 370;
    //准备在画布上绘制图片
    let canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
    //判断上传的图片的宽高是否超过设置的默认最大值，以及设置同比例的宽高
    if (Math.max(imgWidth, imgHeight) > myWidth) {
      if (imgWidth > imgHeight) {
        canvas.width = myWidth;
        canvas.height = (myWidth * imgHeight) / imgWidth;
      } else {
        canvas.height = myWidth;
        canvas.width = (myWidth * imgWidth) / imgHeight;
      }
    } else {
      canvas.width = imgWidth;
      canvas.height = imgHeight;
    }
    //清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    //开始绘制图片到画布上
    ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
    let newBase64 = canvas.toDataURL('image/jpeg', quality); //压缩图片大小（关键代码）
    // 获取到当前的图片的大小，然后调整成自己需要的大小，例如说需要200KB-500KB之间（可以自行设置）
    while (newBase64.length / 1024 > 25) {
      quality -= 0.02;
      newBase64 = canvas.toDataURL('image/jpeg', quality);
    }

    while (newBase64.length / 1024 < 10 && base64.length / 1024 > 10) {
      quality += 0.02;
      newBase64 = canvas.toDataURL('image/jpeg', quality);
    }
    next(newBase64);
  };
};
App.getNewImg100 = function(base64, next) {
  //创建一个图片
  var newImage = new Image();
  var quality = 0.8; //压缩系数0-1之间，压缩到0.9以上会有bug，注意！（可以自行设置）
  newImage.src = base64;
  newImage.setAttribute('crossOrigin', 'Anonymous'); //url为外域时需要
  var imgWidth, imgHeight;
  newImage.onload = function() {
    imgWidth = this.width;
    imgHeight = this.height;
    //给生成图片设置一个默认的最大宽/高（可以自行设置）
    let myWidth = 370;
    //准备在画布上绘制图片
    let canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
    //判断上传的图片的宽高是否超过设置的默认最大值，以及设置同比例的宽高
    if (Math.max(imgWidth, imgHeight) > myWidth) {
      if (imgWidth > imgHeight) {
        canvas.width = myWidth;
        canvas.height = (myWidth * imgHeight) / imgWidth;
      } else {
        canvas.height = myWidth;
        canvas.width = (myWidth * imgWidth) / imgHeight;
      }
    } else {
      canvas.width = imgWidth;
      canvas.height = imgHeight;
    }
    //清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    //开始绘制图片到画布上
    ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
    let newBase64 = canvas.toDataURL('image/jpeg', quality); //压缩图片大小（关键代码）
    console.log(newBase64.length / 1024, '0.8压缩');
    // 获取到当前的图片的大小，然后调整成自己需要的大小，例如说需要200KB-500KB之间（可以自行设置）
    while (newBase64.length / 1024 > 100) {
      alert('大于100k');
      quality -= 0.02;
      newBase64 = canvas.toDataURL('image/jpeg', quality);
    }

    // while (newBase64.length / 1024 < 10 && base64.length / 1024 > 10) {
    //   quality += 0.02;
    //   newBase64 = canvas.toDataURL('image/jpeg', quality);
    // }
    next(newBase64);
  };
};
